package com.mx.base.language.script.remote

import com.mx.base.language.script.XmlHelper
import java.io.File


/**
 * @author: xiao.ma
 * Date: 2022/2/25 15:19
 * Desc:
 */

class PullScript(private val appId: Long) {

    fun genStringsXml(
        moduleFile: File,
        resPath: String,
        baseLanguage: String,
        targets: List<String>,
        update: Boolean = false,
        fill: Boolean = false
    ) {
        val baseXmlMap =
            XmlHelper.readStringXml("${moduleFile.absolutePath}/$resPath/$baseLanguage/strings.xml")
        if (baseXmlMap.isEmpty()) {
            println("没有需要翻译的文本")
            return
        }
        targets.forEach {
            println("===>gen $it")
            val targetXmlMap = LanguageHelper.getRemoteLanguageMap(appId, moduleFile.name, it)
            val targetXmlPath = "${moduleFile.absolutePath}//$resPath/$it/strings.xml"
            XmlHelper.genTargetStringsXml(targetXmlPath, baseXmlMap, targetXmlMap, update, fill)
        }

    }


    class Builder {
        private var projectPath = ""
        private var resPath = "src/main/res"
        private var baseLanguage = "values-zh-rCN"
        private var targets = mutableListOf<String>()

        private var update = false

        private var fill = false

        fun setProjectPath(projectPath: String): Builder {
            this.projectPath = projectPath
            return this
        }

        fun setBaseLanguage(baseLanguage: String): Builder {
            this.baseLanguage = baseLanguage
            return this
        }

        fun setTargets(targets: MutableList<String>): Builder {
            this.targets = targets
            return this
        }

        fun setUpdate(update: Boolean): Builder {
            this.update = update
            return this
        }

        fun setFill(fill: Boolean): Builder {
            this.fill = fill
            return this
        }

        private fun fileFilter(file: File): Boolean {
            return file.isDirectory
                    && !file.name.startsWith(".")
                    && File(
                file.absolutePath, "$resPath/$baseLanguage/strings.xml"
            ).run {
                exists() && isFile
            }
        }

        fun build() {
            val pullScript = PullScript(0L)
            File(projectPath)
                .listFiles { file -> fileFilter(file) }?.forEach {
                    pullScript.genStringsXml(
                        it,
                        resPath = resPath,
                        baseLanguage = baseLanguage,
                        targets = targets,
                        update = update,
                        fill = fill
                    )
                }

        }
    }


}

fun main() {
    PullScript.Builder()
        .setProjectPath("./")
        .build()
}